package lanou3g.myfirstapp36kr.activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.InsetDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;

import lanou3g.myfirstapp36kr.BuildConfig;
import lanou3g.myfirstapp36kr.R;
import lanou3g.myfirstapp36kr.RecordSQLiteOpenHelper;
import lanou3g.myfirstapp36kr.adapter.ActivitySearchLvAdapter;
import lanou3g.myfirstapp36kr.base.BaseActivity;
import lanou3g.myfirstapp36kr.entity.SearchActivityLvEntity;
import lanou3g.myfirstapp36kr.myvolleysingleton.VolleySingleton;

/**
 * Created by dllo on 16/8/8.
 */
public class SearchActivity extends BaseActivity implements OnClickListener {
    private EditText editText;
    private TextView textViewCancel;
    private String stringInput = new String();
    private ImageView imageView;
    private ListView listView;
    private ListView listViewRecord;
    private ActivitySearchLvAdapter adapter;
    private SearchActivityLvEntity response;
    private FrameLayout frameLayout;
    private Button buttonClearRecord;
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private SQLiteDatabase db;
    private BaseAdapter recordAdapter;
    private String stringUrl;

    @Override
    protected int getLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        textViewCancel = (TextView) findViewById(R.id.tv_cancel);
        textViewCancel.setOnClickListener(this);
        editText = (EditText) findViewById(R.id.et_search);
        editText.setOnClickListener(this);
        imageView = (ImageView) findViewById(R.id.iv_delete);
        imageView.setOnClickListener(this);
        listView = (ListView) findViewById(R.id.list_view);
        listViewRecord = (ListView) findViewById(R.id.list_view_record);
        adapter = new ActivitySearchLvAdapter(this);
        frameLayout = (FrameLayout) findViewById(R.id.framelayout_clear_record);
        buttonClearRecord = (Button) findViewById(R.id.btn_clear_record);
        buttonClearRecord.setOnClickListener(this);


    }

    @Override
    protected void initData() {
        queryData("");
        findViewById(R.id.tv_more).setOnClickListener(this);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(SearchActivity.this,NewsDetailsActivity.class);
                if (response != null){
                    String pictureUrl = response.getData().getData().get(i).getFeatureImg();
                    //if (BuildConfig.DEBUG) Log.d("Fragmentnews______", pictureUrl);
                    intent.putExtra("pictureUrl",pictureUrl);
                    String name = response.getData().getData().get(i).getUser().getName();
                    intent.putExtra("name",name);
                    //if (BuildConfig.DEBUG) Log.d("Fragmentnews===", name);
                    String title = response.getData().getData().get(i).getTitle();
                    intent.putExtra("title",title);
                    String feedId = response.getData().getData().get(i).getFeedId();
                    String detailsUrl = "https://rong.36kr.com/api/mobi/news/" + feedId;
                    intent.putExtra("detailsUrl",detailsUrl);
                    long publishTime = response.getData().getData().get(i).getPublishTime();
                    intent.putExtra("publishTime",publishTime);
                    startActivity(intent);
                }else {
                    Toast.makeText(SearchActivity.this, "请输入关键字", Toast.LENGTH_SHORT).show();
                }
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String tempName = editText.getText().toString();
                queryData(tempName);

            }
        });


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.iv_delete:
                stringInput = editText.getText().toString();

                if (stringInput.length() == 0){
                    Toast.makeText(this, "删没了还删什么", Toast.LENGTH_SHORT).show();
                    adapter.setEntity(null);
                    adapter.notifyDataSetChanged();
                    frameLayout.setVisibility(View.VISIBLE);

                }else {
                    stringInput = stringInput.substring(0,stringInput.length() - 1);
                    editText.setText(stringInput);
                }
                break;
            case R.id.et_search:
                frameLayout.setVisibility(View.GONE);

                //将当前查询的关键字保存起来,如果存在就不保存
                boolean hasData = hasData(editText.getText().toString().trim());
                if (!hasData){
                    insertData(editText.getText().toString().trim());
                    queryData("");

                }







                stringInput = editText.getText().toString();
                stringUrl = "https://rong.36kr.com/api/mobi/news/search?keyword=" + stringInput + "&page=1&pageSize=3";
                //if (BuildConfig.DEBUG) Log.d("SearchActivity++++", stringUrl);
                VolleySingleton.addRequest(stringUrl, SearchActivityLvEntity.class, new Response.Listener<SearchActivityLvEntity>() {
                    @Override
                    public void onResponse(SearchActivityLvEntity response) {
                        SearchActivity.this.response = response;
                        if (response != null){
                            adapter.setEntity(response);
                            //if (BuildConfig.DEBUG) Log.d("+++===-->", response);
                            listView.setVisibility(View.VISIBLE);
                            listView.setAdapter(adapter);
                            listViewRecord.setVisibility(View.GONE);
                        }else {

                        }

                    }
                }, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                break;
            case R.id.tv_more:
                Intent intent = new Intent(this,SearchMoreActivity.class);
                stringInput = editText.getText().toString();
                intent.putExtra("stringInput",stringInput);
                startActivity(intent);
                break;
            case R.id.btn_clear_record:
                deleData();
                queryData("");

        }
    }

    /**
     * 插入数据
     * @param tempName
     */



    private void insertData(String tempName){
        db = helper.getWritableDatabase();
        db.execSQL(" insert into records(name) values('" + tempName + "')");
        db.close();
    }

    /**
     * 模糊查询数据
     * @param tempName
     */
    private void queryData(String tempName) {
        final Cursor curson = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ",null
        );
        //创建adapter适配器对象
        recordAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,curson,new String[] {"name"},
                new int[] {android.R.id.text1}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listViewRecord.setVisibility(View.VISIBLE);
        listViewRecord.setAdapter(recordAdapter);
        listView.setVisibility(View.GONE);
        listViewRecord.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Log.d("SearchActivity", recordAdapter.getItem(i).getClass().getSimpleName());
//                SQLiteCursor sqLiteCursor = (SQLiteCursor) recordAdapter.getItem(i);
//                sqLiteCursor.moveToFirst();
//                String string = sqLiteCursor.getString(sqLiteCursor.getColumnIndex("name"));
//                Log.d("SearchActivity++=", string);
//                editText.setText(string);
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String recordString = textView.getText().toString();
                editText.setText(recordString);
                listViewRecord.setVisibility(View.GONE);
                listView.setVisibility(View.VISIBLE);
                stringInput = editText.getText().toString();
                stringUrl = "https://rong.36kr.com/api/mobi/news/search?keyword=" + stringInput + "&page=1&pageSize=3";
                //if (BuildConfig.DEBUG) Log.d("SearchActivity++++", stringUrl);
                VolleySingleton.addRequest(stringUrl, SearchActivityLvEntity.class, new Response.Listener<SearchActivityLvEntity>() {
                    @Override
                    public void onResponse(SearchActivityLvEntity response) {
                        SearchActivity.this.response = response;
                        if (response != null){
                            adapter.setEntity(response);
                            //if (BuildConfig.DEBUG) Log.d("+++===-->", response);
                            listView.setAdapter(adapter);
                        }else {

                        }

                    }
                }, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

            }
        });
        recordAdapter.notifyDataSetChanged();

    }

    /**
     * 检查数据库中是否已经有该条记录
     * @param tempName
     * @return
     */
    private boolean hasData(String tempName){
        Cursor curson = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =? ",new String[] {tempName}
        );
        //判断是否有下一个
        return curson.moveToNext();
    }

    /**
     * 清空数据
     */
    private void deleData(){
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();

    }

}
